import socket


class Server:
    def __init__(self, ip_addr, port):
        self.addr = (ip_addr, port)
        self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_socket.bind(self.addr)

    def write(self, message, addr):
        self.udp_socket.sendto(message, addr)

    def read(self):
        message = self.udp_socket.recvfrom(1024)
        print(f"server Received {message!r}")
        message, client_addr = message
        self.write(message, client_addr)
        print("finished socket echoing to", client_addr)

    def run(self):
        while True:
            try:
                self.read()
            except KeyboardInterrupt:
                return


class Client:
    def __init__(self, ip_addr, port):
        self.addr = (ip_addr, port)
        self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_socket.bind(self.addr)

    def read(self):
        message = self.udp_socket.recvfrom(1024)
        return message

    def write(self, message, server_addr):
        self.udp_socket.sendto(message, server_addr)

    def run(self):
        while True:
            try:
                message = str(input("input the message you want to echo in the form of message,ip address, port:\n"))
                message, ip, port = message.split(",")
                server_add = (ip, int(port))
                self.write(message.encode("utf8"), server_add)
                print("finished socket writing")
                echo_message = self.read()
                message, addr = echo_message
                print(f"Received {message!r} from {addr!r}")
            except KeyboardInterrupt:
                return


if __name__ == "__main__":
    server = Server("127.0.0.1", 65431)
    server.run()
    # client = Client("127.0.0.1", 65432)
    # client.run()
